package cn.eoneplus.mes.ui.module.verification.${classname};

import android.app.Application;
import android.view.View;

import androidx.annotation.NonNull;

<#if isCardView>
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
</#if>

import androidx.lifecycle.MutableLiveData;

<#if isCardView>
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
</#if>

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.eoneplus.app.common.binding.command.BindingAction;
import cn.eoneplus.app.common.binding.command.BindingCommand;
import cn.eoneplus.app.common.binding.viewadapter.spinner.IKeyAndValue;
import cn.eoneplus.app.common.bus.event.SingleLiveEvent;
import cn.eoneplus.app.common.http.BaseResponse;
import cn.eoneplus.app.common.util.CollectionUtil;
import cn.eoneplus.app.common.util.RxUtil;
import cn.eoneplus.app.common.util.StringUtil;
import cn.eoneplus.mes.BR;
import cn.eoneplus.mes.R;
import cn.eoneplus.mes.constant.AppConstant;
import cn.eoneplus.mes.constant.EntityConstant;
import cn.eoneplus.mes.data.AppRepository;
import cn.eoneplus.mes.dto.onlinewms.shelf.ParametersDTO;
import cn.eoneplus.mes.dto.onlinewms.shelf.WmsShelfTopicMsgDTO;
import cn.eoneplus.mes.dto.verification.${classname}.${InfoEntity};
<#if isCardView>
import cn.eoneplus.mes.dto.verification.${classname}.${DetailEntity};
</#if>
import cn.eoneplus.mes.entity.verification.VerificationParserEntity;
import cn.eoneplus.mes.ui.base.viewmodel.ToolbarViewModel;
import cn.eoneplus.mes.util.DeviceUtil;
import cn.eoneplus.mes.util.MyParserUtil;
import cn.eoneplus.mes.util.RetrofitClient;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * ViewModel ${projectName}
 */
public class ${ClassName}ViewModel extends ToolbarViewModel<AppRepository> {
    // 当前页面实体
    private ${InfoEntity} ${infoEntity};

    <#if isScan>
    // 保存变量数据
    private MutableLiveData<String> errorInfo = new MutableLiveData<>();
    </#if>

    <#if isCardView>
    private ObservableList<${ClassName}ItemViewModel> itemList = new ObservableArrayList<${ClassName}ItemViewModel>() { };
    // CardView List
    private MutableLiveData<List<${ClassName}ItemViewModel>> detailList = new MutableLiveData<>();
    public MutableLiveData<${DetailEntity}> ${detailEntity} = new MutableLiveData<>();
    </#if>
    <#if isScan>
    private List<MyParserUtil.MatchResult> matchList;
    </#if>
    <#if childDTOListFlsg != "0">
    <#list childDTOList as child>
    <#if child.type == "下拉框">
    // ${child.nameCN}
    public MutableLiveData<List<IKeyAndValue>> ${child.name}ItemData = new MutableLiveData<>();
    <#else>
    // ${child.nameCN}
    private MutableLiveData<${child.valueType}> ${child.name} = new MutableLiveData<>();
    </#if>
    </#list>
    </#if>
    <#if isCardView>
    /**
    * 封装一个界面发生改变的观察者
    */
    public ${ClassName}ViewModel.UIChangeObservable uc = new ${ClassName}ViewModel.UIChangeObservable();

    public class UIChangeObservable {
    // 当前详情index事件
    public SingleLiveEvent<Integer> currentDetailIndexEvent = new SingleLiveEvent<>();
    }
    </#if>
    /**
     * 是否有dialog打开
     */
    public boolean isShowDialog = false;
    /**
     * 消息对话框，String列表，第一个为标题，第二个为内容
     */
    public SingleLiveEvent<List<String>> infoDialogLiveData = new SingleLiveEvent<>();
    <#if isCardView>
    // RecyclerView多布局添加ItemBinding
    public ItemBinding<${ClassName}ItemViewModel> listItemBinding = ItemBinding.of(BR.viewModel, R.layout.item_verification_${class_name}_list);
    </#if>
    public ${ClassName}ViewModel(@NonNull Application application, AppRepository model) {
        super(application, model);
        <#if isCardView>
        MyParserUtil.getAllVerificationParser(model).subscribe(new Consumer<List<VerificationParserEntity>>() {
            @Override
            public void accept(List<VerificationParserEntity> verificationParserEntities) throws Exception {
                verificationParserList = verificationParserEntities;
            }
        });
        </#if>
    }
    @Override
    public void onCreate() {
        super.onCreate();
        //初始化标题栏
        setIsShowBack(View.VISIBLE);
        // TODO 多语言待处理 getApplication().getResources().getString(R.string.xxxxx)
        setTitleText("${projectName}");
    }
    /**
     * 设置初始数据
     */
    public void setInitData(${InfoEntity} data) {
        loadInitData();
        <#if isCardView>
        this.${infoEntity} = data;
        // 刷新卡片数据
        ObjectMapper mapper = new ObjectMapper();
        List<${DetailEntity}> ${detailEntity} = mapper.convertValue(${infoEntity}.getInnerList(), new TypeReference<List<${DetailEntity}>>() {
        });
        refreshCard(listM);
        </#if>
    }
    /**
     * 加载初始数据
     */
    public void loadInitData() {
        //
    }
    <#if childDTOListFlsg != "0">
    <#list childDTOList as child>
        <#if child.type == "按钮">
    /**
     * ${child.nameCN}[按钮点击事件]
     */
    public BindingCommand ${child.name}ClickCommend = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            // TODO 点击后操作
            infoDialogLiveData.setValue(Arrays.asList("测试","点击了${child.nameCN}"));
        }
    });
        </#if>
        <#if child.type == "下拉框">
    /**
    * ${child.nameCN}[下拉框选择事件]
    */
    public BindingCommand<IKeyAndValue> on${child.name}SelectorCommand = new BindingCommand<>(new BindingConsumer<IKeyAndValue>() {
        @Override
        public void call(IKeyAndValue iKeyAndValue) {
            // TODO 选择后操作
            infoDialogLiveData.setValue(Arrays.asList("测试","${child.nameCN},选择了" + iKeyAndValue.getValue()));
        }
    });
        </#if>
    </#list>
    </#if>
    <#if isScan>
    /**
     * 扫描后下步操作
     */
    private void nextOperation(int itemCode) {
        // TODO 扫描下步操作
    }

    // 扫描相关
    /**
     * 匹配器
     */
    private List<VerificationParserEntity> verificationParserList;
    /**
     * 支持的共通扫描项目（获取旧料信息的扫描项）
     */
    private Set<String> commonScanItemCodeSet = new HashSet<String>() {{
        add(EntityConstant.SCAN_ITEM_UNIQUE_NUMBER);
    }};


    /**
     * 处理物料扫描
     *
     * @param scanValue
     */
    public void receiveScanValue(String scanValue) {
        if (StringUtil.isTrimEmpty(scanValue)) {
            playNGSound();
            return;
        }
        if (CollectionUtil.isEmpty(verificationParserList)) {
            // 无匹配器（未准备好、无数据）
            infoDialogLiveData.setValue(Arrays.asList(getApplication().getResources().getString(R.string.cm_dialog_title_prompt),
                    getApplication().getResources().getString(R.string.cm_msg_verification_parser_not_ready)));
            playNGSound();
            return;
        }
        matchList = MyParserUtil.matchList(verificationParserList, scanValue, 0, 0, commonScanItemCodeSet);
        if (CollectionUtil.isEmpty(matchList)) {
            // 没有匹配到条码数据
            infoDialogLiveData.setValue(Arrays.asList(getApplication().getResources().getString(R.string.cm_dialog_title_prompt),
                    getApplication().getResources().getString(R.string.cm_msg_verification_cannot_match)));
            playNGSound();
            return;
        }
        MyParserUtil.MatchResult processItem = matchList.get(0);
        // 项目code
        String verificationItem = processItem.getVerificationItem();
        // 项目值
        String matchValue = processItem.getMatchValue();
        if (StringUtil.isEmpty(matchValue)) {
            // 匹配值为空
            infoDialogLiveData.setValue(Arrays.asList(getApplication().getResources().getString(R.string.cm_dialog_title_prompt),
                    getApplication().getResources().getString(R.string.cm_msg_verification_cannot_match)));
            playNGSound();
            return;
        }
        switch (verificationItem) {
            case EntityConstant.SCAN_ITEM_UNIQUE_NUMBER:
                //判断是否存在唯一码
                for (int i = 0; i < itemList.size(); i++) {
                    if (itemList.get(i).getFirstMaterialDetail().getValue().getUniqueNumber().equals(matchValue)) {
                        //下步操作
                        nextOperation(i);
                        return;
                    }
                }
                //不存在唯一码信息则报错提示
                infoDialogLiveData.setValue(Arrays.asList(getApplication().getResources().getString(R.string.cm_dialog_title_prompt),
                        getApplication().getResources().getString(R.string.find_material_no_uniquenumber_info))); //未上架获取物料信息
                playNGSound();
                break;
            default:
                infoDialogLiveData.setValue(Arrays.asList(getApplication().getResources().getString(R.string.cm_dialog_title_prompt),
                        getApplication().getResources().getString(R.string.cm_msg_verification_cannot_match)));
                playNGSound();
                break;
        }
    }
    </#if>

    <#if isCardView>
    // 卡片数据相关

    /**
     * 条目点击事件
     */
    public void goIndexDetail(${ClassName}ItemViewModel ${classname}ItemViewModel) {
        final int index = getIndexByDetail(${className}ItemViewModel);
        // TODO 点击条目后操作
    }

    /**
     * 根据索引获取详细
     */
    public int getIndexByDetail(${ClassName}ItemViewModel ${className}ItemViewModel) {
        if (detailList.getValue() != null && ${className}ItemViewModel != null) {
            return detailList.getValue().indexOf(${className}ItemViewModel);
        } else {
            return -1;
        }
    }

    /**
     * 当前index
     */
    public int getCurrIndex() {
        return uc.currentDetailIndexEvent.getValue();
    }

    /**
     * 刷新卡片数据
     *
     * @param detailItemList
     */
    public void refreshCard(List<${DetailEntity}> detailItemList) {
        if (detailItemList == null || detailItemList.size() == 0) {
            infoDialogLiveData.setValue(Arrays.asList(
                    getApplication().getResources().getString(R.string.cm_dialog_title_prompt),
                    getApplication().getResources().getString(R.string.verification_first_material_dialog_text_no_data)));
            playNGSound();
            return;
        }
        List<${ClassName}ItemViewModel> viewModelList = new ArrayList<>();
        for (int i = 0; i < detailItemList.size(); i++) {
            viewModelList.add(new ${ClassName}ItemViewModel(${ClassName}ViewModel.this, detailItemList.get(i)));
        }
        itemList.addAll(viewModelList);
    }
    </#if>

    /**
     * GETTER方法
     */
    <#if isCardView>
    private ObservableList<${ClassName}ItemViewModel> getItemList() {
        return itemList;
    }

    private MutableLiveData<List<${ClassName}ItemViewModel>> getDetailList (){
        return detailList;
    }

    public MutableLiveData<${DetailEntity}> get${DetailEntity} () {
        return ${detailEntity};
    }
    </#if>

    <#if childDTOListFlsg != "0">
    <#list childDTOList as child>
    <#if child.type != "下拉框">
    public MutableLiveData<${child.valueType}> get${child.humpName}() {
        return ${child.name};
    }
    </#if>
    </#list>
    </#if>

    <#if isScan>
    public void setErrorInfo(String errorInfo) {
        this.errorInfo.setValue(errorInfo);
    }

    public void setErrorInfo(MutableLiveData<String> errorInfo) {
        this.errorInfo = errorInfo;
    }
    </#if>
}